package com.yyge.config.security.service.impl;

import com.yyge.config.Constants;
import com.yyge.config.security.dto.SecurityUser;
import com.yyge.entity.Role;
import com.yyge.entity.User;
import com.yyge.entity.UserRole;
import com.yyge.mapper.RoleMapper;
import com.yyge.mapper.UserMapper;
import com.yyge.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * <p> 自定义userDetailsService - 认证用户详情 </p>
 *
 * @author : gityyge
 * @description :
 * @date : 2019/10/14 17:46
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    /***
     * 根据账号获取用户信息
     * @param username: 用户名
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.printf("22");
        // 从数据库中取出用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.last("limit 1");
        User user = userMapper.selectOne(queryWrapper);
        //String password = PasswordUtils.encodePassword("123456", "ssdsdsadasd");
        //System.out.println(password);
        // 判断用户是否存在
        if (Objects.nonNull(user)) {
            // 账号 flag 标识为0不让登陆
            if (StringUtils.isEmpty(user.getFlag()) || user.getFlag().equals("0")) {
                log.error("该账号已被禁止登陆！");
                throw new UsernameNotFoundException("该账号已被禁止登陆！");
            }
            List<Role> roles = roleMapper.selectRoleByUserId(user.getId());
            for (Role role : roles) {
                // 客户禁止登陆此平台
                if (role.getType().equals(Constants.ROLE_LOGIN_CUSTOMER)) {
                    log.error("该账号禁止登陆此平台！");
                    throw new UsernameNotFoundException("该账号禁止登陆此平台！");
                }
            }
        } else {
            log.error("用户名不存在！");
            throw new UsernameNotFoundException("用户名不存在！");
        }

        // 返回UserDetails实现类
        return new SecurityUser(user, getUserRoles(user.getId()));
    }

    /***
     * 根据token获取用户权限与基本信息
     *
     * @param token:
     * @return: SecurityUser
     */
    public SecurityUser getUserByToken(String token) {
        User user = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);
        List<User> loginList = userMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(loginList)) {
            user = loginList.get(0);
        }
        return user != null ? new SecurityUser(user, getUserRoles(user.getId())) : null;
    }

    /**
     * 通过User获取SecurityUser
     *
     * @param user
     * @return
     */
    public SecurityUser getSecurityUserByUser(User user) {
        return user != null ? new SecurityUser(user, getUserRoles(user.getId())) : null;
    }

    /**
     * 根据用户id获取角色权限信息
     *
     * @param userId
     * @return
     */
    private List<Role> getUserRoles(Long userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        List<Role> roleList = new LinkedList<>();
        for (UserRole userRole : userRoles) {
            Role role = roleMapper.selectById(userRole.getRoleId());
            roleList.add(role);
        }
        return roleList;
    }

}
